package ink.tsg.springexecutor.config;

import ink.tsg.springexecutor.handler.MyRejectedExecutionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author ruoyi
 **/
@Configuration
@EnableAsync    // 开启异步
public class ThreadPoolConfig
{
    // 核心线程池大小
    private final int CORE_POOL_SIZE = 5;

    // 最大可创建的线程数
    private final int MAX_POOL_SIZE = 20;

    // 队列最大长度
    private final int QUEUE_CAPACITY = 5;

    // 线程池维护线程所允许的空闲时间
    private final int KEEP_ALIVE_SECONDS = 30;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        executor.setThreadGroupName("测试---");
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new MyRejectedExecutionHandler());
        return executor;
    }
}
